<template>
  <div style="width: 500px">
    <el-input
        placeholder="请输入部门名称进行搜索..."
        prefix-icon="el-icon-search"
        v-model="filterText">
    </el-input>

    <el-tree
        :data="deps"
        :props="defaultProps"
        :filter-node-method="filterNode"
        :expand-on-click-node="false"
        ref="tree">
      <!--      default-expand-all-->
      <span class="custom-tree-node" slot-scope="{ node, data }"
            style="display: flex;justify-content: space-between;width: 100%">
          <span>{{ data.organizationName }} </span>
          <span>
            <el-button
                type="primary"
                size="mini"
                class="depBtn"
                @click="() => showAddDep(data)">
              添加部门
            </el-button>
                <el-button
                        type="warning"
                        size="mini"
                        class="depBtn"
                        @click="() => showEditorDep(data)">
              编辑部门
            </el-button>
            <el-button
                type="danger"
                size="mini"
                class="depBtn"
                @click="() => deleteDep(data)">
              删除部门
            </el-button>
          </span>
        </span>
    </el-tree>
    <el-dialog
        title="添加部门"
        :visible.sync="dialogVisible"
        width="80%">
      <div style="display:flex;flex-direction:row">
        <div style="border-right: 2px dashed #ccc;width:45%;display:flex;justify-content: center;">
          <div class=""  style="margin: 0 10px 10px 0">
            <span class="">
             <span style="color: #0093f0"><i class="el-icon-edit"></i> 基本信息</span>
           </span>
          </div>
          <el-form :model="dep" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="部门编码:" prop="organizationId">
              <el-input v-model="dep.organizationId"></el-input>
            </el-form-item>
            <el-form-item label="部门名称:" prop="organizationName">
              <el-input v-model="dep.organizationName"></el-input>
            </el-form-item>
            <el-form-item label="上级部门:" prop="pname">
              <el-input v-model="pname" disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item label="部门所属:" prop="organizationType">
              <el-input v-model="dep.organizationType" disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item label="责任人:" prop="principald">
              <el-input v-model="dep.principald"></el-input>
            </el-form-item>
            <el-form-item label="编制人数:" prop="enmNumber">
              <el-input v-model="dep.enmNumber"></el-input>
            </el-form-item>
            <el-form-item  label="生效时间:" prop="effectiveTime" >
              <el-date-picker
                      v-model="dep.effectiveTime"
                      type="datetime"
                      placeholder="生效时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item  label="失效时间:" prop="failureTime" >
              <el-date-picker
                      v-model="dep.failureTime"
                      type="datetime"
                      placeholder="失效时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="备注信息">
              <el-input type="textarea" v-model="dep.remark" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item v-if="isAdd">
              <el-button type="primary" @click="doAddDep">立即创建</el-button>
              <el-button @click="initDep">重置</el-button>
            </el-form-item>
            <el-form-item v-if="isEditor">
              <el-button type="primary" @click="editorDep">立即修改</el-button>
              <el-button @click="closeDialog">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div  style="margin: 0 10px 10px 20px">
          <div class=""  style="margin: 0 20px 10px 0">
            <span class="">
             <span style="color: #0093f0"><i class="el-icon-edit"></i> 附件信息</span>
           </span>
          </div>
          <el-form :model="departAttachs" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="所在区域:" prop="organAreasId">
              <el-select v-model="departAttachs.organAreasId" placeholder="职称" size="mini" style="width: 300px;">
                <el-option
                        v-for="item in hostCities"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="通讯地址:" prop="mailAddress">
              <el-input v-model="departAttachs.mailAddress"></el-input>
            </el-form-item>
            <el-form-item label="固定电话:" prop="telephone">
              <el-input v-model="departAttachs.telephone" ></el-input>
            </el-form-item>
            <el-form-item label="传真号码:" prop="faxTelephone">
              <el-input v-model="departAttachs.faxTelephone" ></el-input>
            </el-form-item>
            <el-form-item label="电子邮件:" prop="mail">
              <el-input v-model="departAttachs.mail"></el-input>
            </el-form-item>
            <el-form-item label="网址:" prop="webUrl">
              <el-input v-model="departAttachs.webUrl"></el-input>
            </el-form-item>
            <el-form-item label="备注信息">
              <el-input type="textarea" v-model="departAttachs.remark" style="width: 300px"></el-input>
            </el-form-item>
            <el-form-item  label="创建时间" prop="time" >
              <el-date-picker
                      v-model="time"
                      type="datetime"
                      placeholder="生效时间"
                      disabled="disabled">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="创建人">
              <el-input  v-model="user.name" disabled="disabled"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div>
      </div>
<!--      <span slot="footer" class="dialog-footer">-->
<!--    <el-button @click="dialogVisible = false">取 消</el-button>-->
<!--    <el-button type="primary" @click="doAddDep">确 定</el-button>-->
<!--  </span>-->
    </el-dialog>
  </div>
</template>
<script>
  import {postRequest, putRequest} from "../../utils/api";

export default {
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
    dialogVisible:function(val) {
      if (!val){
        this.isAdd=false
        this.isEditor=false
      }
    }
  },
  name: "DepMana",
  data() {
    return {
      hostCities: [],
      user:JSON.parse(window.sessionStorage.getItem('user')),
      pname: '',
      dep: {
        organizationId:'',
        organizationName:'',
        parentId:'-1',
        dePath:'',
        organizationType:'总公司',
        principaId:'',
        isParent:'',
        effectiveTime: '',
        failureTime: '',
        remark:'',
      },
      dialogVisible: false,
      isAdd: false,
      isEditor: false,
      filterText: '',
      deps: [],
      defaultProps: {
        children: 'children',
        label: 'organizationName'
      },
      departAttach:{
        organAreasId:'',
        mailAddress:'',
        telephone:'',
        faxTelephone:'',
        mail:'',
        webUrl:'',
      },
      departAttachs:{
        organAreasId:'',
        mailAddress:'',
        telephone:'',
        faxTelephone:'',
        mail:'',
        webUrl:'',
      },
      time:new Date,
      rules: {
        organizationId: [
          {required: true, message: '请输入部门编号', trigger: 'blur'},
        ],
        organizationName: [
          {required: true, message: '请输入部门名称', trigger: 'change'}
        ],
        effectiveTime: [
          {type: 'date', required: true, message: '请选择时间', trigger: 'change'}
        ],
        failureTime: [
          {type: 'date', required: true, message: '请选择时间', trigger: 'change'}
        ],
      }
    }
  },
  mounted() {
    this.initDeps();
  },
  methods: {
    initDep() {
      this.dep = {
        organizationId:'',
        organizationName:'',
        parentId:'-1',
        dePath:'',
        organizationType:'总公司',
        principaId:'',
        isParent:'',
        effectiveTime: '',
        failureTime: '',
        remark:'',
      };
      this.departAttachs={
        departmentId:'',
        mailAddress:'',
        telephone:'',
        faxTelephone:'',
        mail:'',
        webUrl:'',
      };
      this.pname = '';
      this.time=''
    },
    addDep2Dep2(deps, dep) {
      for (let i = 0; i < deps.length; i++) {
        let d = deps[i];
        if (d.id == dep.parentId) {
          if (d.children == null) {
            d.children = [];
          }
          d.isParent = true;
          d.children = d.children.concat(dep);
          return;
        } else {
          if (d.children != null) {
            this.addDep2Dep2(d.children, dep);
          }
        }
      }
    },
    closeDialog(){
      this.dialogVisible = false;
    },
    doAddDep() {
        let depAndAttach ={
          department: this.dep,
          departAttach: this.departAttachs,
        }
        this.postRequest('/org/dep/addDep/',depAndAttach).then(resp => {
          if (resp) {
            this.addDep2Dep2(this.deps, resp.obj);
            this.dialogVisible = false;
            this.initDep();
          }
        });
    },
    editorDep(){
      //修改部门信息
      let depAndAttach ={
        department: this.dep,
        departAttach: this.departAttachs,
      }
      this.putRequest('/org/dep/editorDep/',depAndAttach).then(resp => {
        if (resp) {
          this.addDep2Dep2(this.deps, resp.obj);
          this.dialogVisible = false;
          this.initDep();
        }
      });

    },
    showAddDep(data) {
      this.initDep();
      this.pname = data.organizationName
      this.dep.parentId = data.id;
      this.isAdd=true;
      this.dialogVisible = true;
    },
    showEditorDep(data){
      this.initDep();
      this.pname = data.organizationName
      this.dep=data;
      this.isEditor=true;
      this.dialogVisible = true;
    },
    deleteDep(data) {
      if (data.isParent) {
        this.$message.error('父部门删除失败！');
      } else {
        this.$confirm('此操作将永久删除[' + data.organizationName + ']部门, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteRequest(' /org/dep/' + Number(data.id)).then(resp => {
            if (resp) {
              this.removeDepFromDeps(null, this.deps, data.id);
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }
    },
    removeDepFromDeps(p, deps, id) {
      for (let i = 0; i < deps.length; i++) {
        let d = deps[i];
        if (d.id == id) {
          deps.splice(i, 1);
          if (deps.length == 0) {
            p.isParent = false;
          }
          return;
        } else {
          if (d.children != null) {
            this.removeDepFromDeps(d, d.children, id);
          }
        }
      }
    },
    initDeps() {
      this.getRequest('/org/dep/allDep').then(resp => {
        if (resp) {
          this.deps = resp;
        }
      });
        if (!window.sessionStorage.getItem("hotCities")) {
            this.getRequest('/emp/hotCities').then(resp => {
                if (resp) {
                    this.hostCities=resp;
                    window.sessionStorage.setItem("hotCities", JSON.stringify(resp));
                }
            })
        } else {
            this.hostCities = JSON.parse(window.sessionStorage.getItem("hotCities"));
        }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.organizationName.indexOf(value) !== -1;
    }
  },

}
</script>
<style scoped>
.depBtn {
  padding: 2px;
}
.el-input{
  width:300px;
}
  .el-form-item__content {
    margin-left: 2px!important;
  }
</style>